package dev.kaayf.examples;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuInflater;

import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.PopupMenu;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import dev.kaayf.db.NoteDb;
import dev.kaayf.db.UserPrefs;
import dev.kaayf.utils.Note;

public class MainActivity extends AppCompatActivity {
    private ImageButton createButton;
    private RecyclerView recyclerView;
    private TextView noteCounts, userAlias;
    private List<Note> noteList = new ArrayList<>();
    private CyclerAdapter cyclerAdapter;
    private NoteDb noteDb;
    private UserPrefs userPrefs;

    private int currentNoteCount;

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_main);
        findViews();

        userPrefs = new UserPrefs(this);
        if (userPrefs.isFirstLaunch()) {
            // if first time to launch , jump tu login page, and terminate current activity
            Intent intent = new Intent(MainActivity.this, LoginActivity.class);
            startActivity(intent);
        }else{
            userAlias.setText("Hi," + userPrefs.getUserName());
        }

        // init new NoteDB when activity is loaded
        noteDb = new NoteDb(this);
        noteList = noteDb.getAllNotes();
        currentNoteCount = noteList.size();

        recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
        cyclerAdapter = new CyclerAdapter();
        recyclerView.setAdapter(cyclerAdapter);

        noteCounts.setText("total " + currentNoteCount + " notes");

        createButton.setOnTouchListener((view, motionEvent) -> {
            Intent intent = new Intent(MainActivity.this, CreateActivity.class);
            startActivity(intent);
            return false;
        });

        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
            Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
            return insets;
        });

    }

    // executed when back from another activity that called finish()
    @Override
    protected void onResume() {
        super.onResume();
        updateRecord();
        userAlias.setText("Hi," + userPrefs.getUserName());

    }

    private void updateRecord() {
        noteList = noteDb.getAllNotes();
        updateNoteCounts();
        cyclerAdapter.notifyDataSetChanged();
    }

    private void updateNoteCounts() {
        noteList = noteDb.getAllNotes();
        currentNoteCount = noteList.size();
        noteCounts.setText("total " + currentNoteCount + " notes");
    }

    private void findViews() {
        createButton = findViewById(R.id.create_new_note);
        recyclerView = findViewById(R.id.item_list_container);
        noteCounts = findViewById(R.id.note_counts);
        userAlias = findViewById(R.id.main_layout_user_alias);
    }


    class CyclerAdapter extends RecyclerView.Adapter<CyclerAdapter.ViewHolder> {

        @NonNull
        @Override
        public CyclerAdapter.ViewHolder onCreateViewHolder(@androidx.annotation.NonNull ViewGroup viewGroup, int i) {
            @SuppressLint("ResourceType") ViewHolder viewHolder = new ViewHolder(LayoutInflater.from(MainActivity.this).inflate(R.layout.item_layout, viewGroup, false));

            return viewHolder;
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder viewHolder, int i) {
            Note note = noteList.get(i);
            viewHolder.noteTitle.setText(note.getNoteName());
            viewHolder.noteTime.setText(note.getNoteDate());
            viewHolder.noteIndex = note.getNoteId();

            // set LongClick listener for Note layout for more ops like delete and about
            viewHolder.itemView.setOnLongClickListener(view -> {
                showPopUpMenu(view, note.getNoteId());
                return true;
            });

            // set Click listener to implement jump to edit activity
            viewHolder.itemView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(MainActivity.this, EditActivity.class);
                    intent.putExtra("note", note);
                    intent.putExtra("new", false);
                    startActivity(intent);
                }
            });

        }

        private void showPopUpMenu(View view, int index) {
            // create popup menu instance
            PopupMenu popupMenu = new PopupMenu(MainActivity.this, view);
            MenuInflater menuInflater = popupMenu.getMenuInflater();

            // load from menu resource
            menuInflater.inflate(R.menu.menu_note_ops, popupMenu.getMenu());

            // bind click listener for each item in menu
            popupMenu.setOnMenuItemClickListener(menuItem -> {
                switch (menuItem.getItemId()) {

                    // delete item has clicked
                    case R.id.menu_delete_action:
                        Log.d("CyclerView", "Delete index " + index);
                        noteDb.deleteNote(index);
                        updateRecord();
                        break;

                    // About item has clicked, do nothing here!
                    case R.id.menu_about_action:
                        Log.d("CyclerAdapter", "About " + index);
                        break;
                }
                return true;
            });

            popupMenu.show();
        }


        @Override
        public int getItemCount() {
            return noteList.size();
        }

        class ViewHolder extends RecyclerView.ViewHolder {
            private TextView noteTitle, noteTime;
            private int noteIndex;

            @SuppressLint("ClickableViewAccessibility")
            public ViewHolder(@NonNull View itemView) {
                super(itemView);
                noteTime = itemView.findViewById(R.id.note_time);
                noteTitle = itemView.findViewById(R.id.note_title);

            }


        }

    }
}